var retail;  //总单据明细
var retail_data;  //商品明细
var archives; //档案信息
var optometry; //验光信息
$(function(){
	//获取单据明细
	$.post(get_retail_info_url, {'sales_id':sales_id}, function (res) {
		if(res.code == 1) {
			layer.msg(res.msg);return false;
		}
		retail = res.data.retail;
		retail_data = res.data.retail_data;
		archives = retail.Archives;
		optometry = res.data.optometry;

		//设置用户信息
		var userinfo = [];
		userinfo.push('<li><span class="b"><i class="am-icon-user-md" style="margin-right:7px"></i>'+ archives.Realname +'</span>');
		userinfo.push('<span>电话：'+ archives.Mobile +'</span>');
		if(retail.PickUpType == 1) {
			userinfo.push('<span>取货方式：现场取货</span></li>');
		}else if(retail.PickUpType == 2) {
			userinfo.push('<span>取货方式：邮递取货</span></li>');
		}else if(retail.PickUpType == 3) {
			userinfo.push('<span>取货方式：指定时间取货</span></li>');
			userinfo.push('<li>预计取镜时间：<span class="orange-tips">'+ timetransDate(retail.HopePickUpTime) +'</span></li>');
		}
		userinfo.push('<li>销售员：'+ retail.BusinessName +'</li>');
		userinfo.push('<li>备注：<span class="orange-tips">'+ retail.Remarks +'</span></li>');
		$('#user-info').html(userinfo.join(''));

		//设置支付信息
		var pay_money_box = [];
		pay_money_box.push('<li>零售总金额：￥'+ formatnumber(retail.TotalMoney, "#,##0.00") +'</li>');
		pay_money_box.push('<li>应付金额：￥'+ formatnumber(retail.SumPayable, "#,##0.00") +'</li>');
		pay_money_box.push('<li>优惠金额：￥'+ formatnumber(retail.ChangesMoney, "#,##0.00") +'</li>');
		pay_money_box.push('<li>已付金额：￥'+ formatnumber(retail.AlreadyMoney, "#,##0.00") +'</li>');
		var needMoney = retail.SumPayable - retail.AlreadyMoney;
		pay_money_box.push('<li>待付款：<span style="color:red;">￥'+ formatnumber(needMoney, "#,##0.00") +'</span></li>');
		if(retail.AlreadyMoney != 0) {  //需要付款
			$('.confirm-pay-btn').hide();
			$('.confrim-pick-up-goods').show();
		} else {
			$('.confirm-pay-btn').show();
			$('.confrim-pick-up-goods').hide();
		}
		$('#pay_money_box').html(pay_money_box.join(''));

		$.each(retail_data, function (index, value) {
			value.Products.Name = productGroupName(value.Products);
			value.subparams = [];
			if (value.Products.TypeId == 10) {
				value.subparams.push(value.Snd.sph);
				value.subparams.push(value.Snd.cyl);
			} else if (value.Products.TypeId == 30) {
				value.subparams.push(value.Snd.model);
				value.subparams.push(value.Snd.color);
				if (value.Snd.size) {
					value.subparams.push(value.Snd.size);
				}
			} else if (value.Products.TypeId == 41) {
				value.subparams.push(value.Snd.model);
				value.subparams.push(value.Snd.color);
				if (value.Snd.size) {
					value.subparams.push(value.Snd.size);
				}
				if (value.Snd.function_info) {
					value.subparams.push(value.Snd.function_info);
				}
			} else if (value.Products.TypeId  == 40) {
				value.subparams.push(value.Snd.sph);
				value.subparams.push(value.Snd.add);
			} else if (value.Products.TypeId  == 20) {
				value.subparams.push(value.Snd.sph);
				value.subparams.push(value.Snd.cyl);
			}
			addGoods(value);
		});

	}, 'json');
	

	
});
var addGoods = function (goods) {
	var box = $(".template").clone();
	box.removeClass("template");
	/*********将需要的数据加载到tr行上面去，循环组装数据***************/
	box.attr("data_type",'goods');
	if(parent.page_type=="retail"&&retail.PickUpType==3){//如果是从零售页面过来的，则不能够取货，统一到取镜管理里面去取货
		box.attr("collect_goods_num",0);
	}else{
		box.attr("collect_goods_num",goods.Amount-goods.CollectNum);
	}
	box.attr("discount",goods.DiscountRate);  //折扣
	box.attr("goods_id",goods.Products.Id);
	box.attr("goods_snd_id",goods.Snd.Id);
	box.attr("data_id",goods.Id);
	box.attr("sale_num",goods.Amount);
	box.attr("sell_price",goods.OriginalPrice);
	box.attr("single_price",goods.UnitPrice);
	box.attr("subtotal",goods.TotalPrice);
	/*********************************************/
	box.find(".item-field > h4 > a").text(goods.Products.Name);
	box.find(".form-goods > .formline > span[class='order-number am-margin-right-sm']").text("X"+goods.Amount);
	box.find(".price-info .form-goods > .formline > .price-red").text("￥" + formatnumber(goods.TotalPrice, "#,##0.00"));
	box.find(".price-info .form-goods > .formline > .am-margin-left-sm").text("折扣率"+goods.DiscountRate+"%");

	if(goods.Inventory.Acceptance != null) {
		if(goods.Inventory.Acceptance.Id == 0){
			box.find(".price-info a[type='lot_number']").parent().remove();
			box.find("td:last").find(".btnbar").remove();
		}else {
			box.find(".price-info a[type='lot_number']").text("批号:"+goods.Inventory.Acceptance.lot_number+' 有效期：'+timetransDate(goods.Inventory.Acceptance.expiry_date));
		}
	} else {
		box.find(".price-info a[type='lot_number']").parent().remove();
		box.find("td:last").find(".btnbar").remove();
	}

	if(goods.Amount-goods.CollectNum==0){
		box.find(".price-info .form-goods > .formline > input[name='collect_goods_num']").val(0);
		box.find(".price-info .form-goods > .formline > input[name='collect_goods_num']").attr("readonly","readonly");
		box.find(".price-info .form-goods > .formline > input[name='collect_goods_num']").css("background-color","#eeeeee");
		if(goods.Inventory.Acceptance.Id > 0){
			box.find(".price-info a[type='lot_number']").text("批号:"+goods.Inventory.Acceptance.lot_number);
			box.find("td:last").find(".btnbar").remove();
		}
	}else if(parent.page_type=="retail"&&retail.PickUpType==3){//如果是从零售页面过来的，则不能够取货，统一到取镜管理里面去取货
		box.find(".price-info .form-goods > .formline > input[name='collect_goods_num']").val(0);
		box.find(".price-info .form-goods > .formline > input[name='collect_goods_num']").attr("readonly","readonly");
		box.find(".price-info .form-goods > .formline > input[name='collect_goods_num']").css("background-color","#eeeeee");
		if(goods.Inventory.Acceptance && goods.Inventory.Acceptance.Id > 0 ){
			box.find("td:last").find(".btnbar").remove();
		}
	}else{
		box.find(".price-info .form-goods > .formline > input[name='collect_goods_num']").val(goods.Amount-goods.CollectNum);
	}
	for (var o in goods.subparams) {
		box.find(".item-field > .par > li").append("<span>" + goods.subparams[o] + "</span>");
	}
	if (!goods.Custom.Id) {
		box.find(".customize-tips").hide();
	} else {
		box.find(".customize-tips").show();
	}

	$(".datalist-goods > tbody").append(box);
	box.show();
};

function choosePayType(payType){
	var data=$("#payform").serializeObject();
	var need_price;
	if($("input[name='"+payType+"_pay_price']").val()&&$("input[name='"+payType+"_pay_price']").val()!=0){
		need_price = Number($("input[name='"+payType+"_pay_price']").val());
	}else{
		var this_pay_price =  parseFloat(data.wechat_pay_price)+parseFloat(data.alipay_pay_price)+parseFloat(data.cash_pay_price)+parseFloat(data.bandcard_pay_price);
		need_price = retail.SumPayable  - retail.AlreadyMoney - this_pay_price;
	}
	layer.prompt({title: '输入支付金额', formType: 0, value:need_price+''}, function(payn, index){
		layer.close(index);
		if(payn!=0){
			$("span[pay_type='"+payType+"']").show();
			$("span[pay_type='"+payType+"']").text("付款"+"￥" + formatnumber(payn, "#,##0.00"));
			$("input[name='"+payType+"_pay_price']").val(payn);
		}else{
			$("span[pay_type='"+payType+"']").hide();
			$("input[name='"+payType+"_pay_price']").val(payn);
		}
		mathReturnPrice();
	});
}

function mathReturnPrice(){
	var data=$("#payform").serializeObject();
	var pay_price = parseFloat(data.wechat_pay_price)+parseFloat(data.alipay_pay_price)+parseFloat(data.cash_pay_price)+parseFloat(data.bandcard_pay_price);
	$("[name='pay_price']").val(pay_price);
	$(".pay-method-btn").find("div:first").find("span").text("￥" + formatnumber(pay_price, "#,##0.00"));
}

function changeTRdataInfo(rtn){//修改每一行Tr 上的数据
	$(".datalist-goods").find("tr").each(function(){
		if($(this).attr("data_id")){
			if($(this).attr("data_type")=="goods"){
				$(this).attr("collect_goods_num",$(this).find("input[name='collect_goods_num']").val());
			}
		}
	});
}

function closeThisModal() {
	if(parent.pageType == 'retail') {
		parent.is_leave = false;
	}
	var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
	parent.layer.close(index); //再执行关闭
	return false;
}

function save(){
	var data=$("#payform").serializeObject();
	data.retail_id = retail.Id;
	data.goods_sale_list=[];
	$(".datalist-goods").find("tr").each(function(){
		if($(this).attr("data_id")){
			var goods_json={};
			if($(this).attr("data_type")=="goods"){
				goods_json.collect_goods_num=Number($(this).attr("collect_goods_num"));
				goods_json.id=Number($(this).attr("data_id"));
				data.goods_sale_list.push(goods_json);
			}
		}
	});
	data.goods_sale_list = JSON.stringify(data.goods_sale_list);
	if(retail.PickUpType==1){  //现场取货
		if(data.pay_price<retail.SumPayable){
			layer.alert("因现场取货，请结清所有款项");
			return;
		}else if(data.pay_price>retail.SumPayable){
			layer.alert("付款金额大于待付金额");
			return;
		}

		submitRetail(data);

	}else{
		if(data.pay_price>retail.SumPayable){
			layer.alert("付款金额大于待付金额");
			return;
		}
		submitRetail(data);
	}
}

var submitRetail = function (data) {
	$.post(get_retail_pay_comfirm_url, data, function (res) {
		if(res.code == 1) {
			layer.alert(res.msg);return false
		}
		layer.confirm('结算成功,是否打印零售单？', function (index) {
			//打印结算单
			$.post(get_retail_info_url, {'sales_id':sales_id}, function (res) {
				if(res.code==0) {
					retail = res.data.retail;
					retail_data = res.data.retail_data;
					archives = retail.Archives;
					optometry = res.data.optometry;
					createRetailPrinter({'archives':archives, 'optometry':optometry, 'retail':retail, 'retail_data':retail_data});
					parent.is_leave = true;
					layer.close(index);
					top.location = get_jump_url;
				}
			});
		},function (index) {
		    top.location = get_jump_url;
			layer.close(index);
		});

	}, 'json');
};